<?php
class RL_Principal_Auth_Digest extends RL_Principal_Auth_Common
{
	public $error = NULL;
	public $base_domain = NULL;
	public $cookie_domain = NULL;

	public function __construct ($args)
	{
		$this->store = $args['store'];
		$this->cookie_expire_days = $args['cookie_expire_days'];
		$this->cookie_domain = $args['cookie_domain'];
		$this->cookie_name = $args['cookie_name'];
	} // end of __construct
	public function identify ($input)
	{
		$this->cred = NULL;

		$digest = $input->digest;
		if ($data = $this->store->loadByDigest($digest)) {
			$this->cred = $data;
		}
		return $this->cred;
	} // end of function identify
	public function getProfile ($cred)
	{
		return $this->cred;
	} // end of function getProfile
	
	private function store_generate_stored_invariant($store, $password)
	{
		$magic_word = $store->magic_word;
		$gen = $password.$magic_word;
		return md5($gen);
	}
	
	public function setOKState($cred)
	{
		$digest = $this->store_generate_stored_invariant($this->store, $cred['password']);
		$cred = $this->store->SetStoredDigest($cred, $digest);
		$cred['digest'] = $digest;

		// set new cookie
		if (!isset($_COOKIE[$this->cookie_name]) || $_COOKIE[$this->cookie_name] !== $cred['digest']) {
			debug(__METHOD__." set cookie {$this->cookie_name}: '{$cred['digest']}' for {$this->cookie_domain}");
			setcookie($this->cookie_name, $cred['digest'],
				time() + $this->cookie_expire_days * 86400 , // = 24 * 60 * 60
				'/',
				$this->cookie_domain );
		}
		return $cred;
	} // end of function chauthtok

	public function session_start ()
	{
	} // end of function session_start
	public function session_end ()
	{
		if (isset($_COOKIE[$this->cookie_name])) {
			debug(__METHOD__." unset cookie name='{$this->cookie_name}', domain='{$this->cookie_domain}'");
			setcookie($this->cookie_name, '', time()-3600, '/', '.'.$this->base_domain );
			setcookie($this->cookie_name, '', time()-3600, '/', $this->base_domain );
			setcookie($this->cookie_name, '', time()-3600, '/', $this->cookie_domain);
		}
	} // end of function session_end
}

